import { contextBridge, ipcRenderer } from "electron";

const channel = new MessageChannel()
const port1 = channel.port1
const port2 = channel.port2
port2.start()
ipcRenderer.postMessage("port", null, [port1]);

/* 
  blob不能传；
  发送给渲染线程的event等对象属性会被过滤
  Node.js Buffer 对象将作为 Uint8Array 进行传输
*/
contextBridge.exposeInMainWorld("electronAPI", {
  sendIpcMessage: (message: Message) => ipcRenderer.send("ipc-message", message),
  onIpcMessage: (callback: (message: Message) => unknown) => ipcRenderer.on("ipc-message", (event, message: Message) => callback(message)),
  postPortMessage: (message: Message) => port2.postMessage(message),
  onPortMessage: (callback: (message: Message) => unknown) => port2.addEventListener('message', (event) => callback(event.data)),
  invokeIpc: (type, ...params) => ipcRenderer.invoke(type, ...params), // invoke有返回值
});
